<?php
	//Database
	require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/database.php';
	
	$_SESSION['user'] = null;
	
	//If data exist
	if (isset ($_POST['user']) &&
		isset($_POST['password'])) {

		//Clears from injection
		$username	= mysql_real_escape_string($_POST['user']);
		$password	= md5($_POST['password']);
		
		//Query
		$result	= mysql_query("SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 1") or die(mysql_error());
		$rows	= mysql_num_rows($result);
		
		//Check result
		if ($rows == 1) {
			$row = mysql_fetch_array($result);
			$_SESSION['user'] = $row['id'];
			$_SESSION['login_notification'] = true;
		} else {
			$_SESSION['login_notification'] = false;
		}
	}

	//Start HTML part
	require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/doctype.php';
?>
	<head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>deviantPIC - Login result</title>
    </head>
    <body>
		<!-- Header -->
		<?php require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/header.php'; ?>

		<!-- Content -->
		<div id="body">
			<h2>Login</h2>
			<div id="login-result">
				<?php
					//Get user
					if ($_SESSION['login_notification']) {
						echo "	Thank You
								<div id='login-handler'> Login Success. Please wait here while we transfer you. </div>";
						$login = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE id = '" . $_SESSION['user'] . "'"));
						echo "<meta http-equiv='refresh' content='3; profile/index.php?id=" . $login['id'] . "'/>";
					} else {
						echo "
						Login failed. Please retry.
						<div id='form-login-retry'>
							<form action='/deviantpic/user/login.php' method='post'><p>
								<label for='login_user' >Username: </label>		<input type='text' id='login_user' name='user'/> <br />
								<label for='login_password' >Password: </label>	<input type='password' id='login_password' name='password'/> <br />
							<input type='submit' value='Login' />
							</p></form>
						</div>";
					}
				?>
			</div>
		</div>

		<!-- Footer -->
		<?php require $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/footer.php'; ?>
		
    </body>
</html>
